package daos;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.Session;

import servicios.Operation;

public class SessionManager {
	
	private static SessionFactory sessionFactory;
	private static ThreadLocal<Session> tlSession = new ThreadLocal<Session>();
	private static ServiceRegistry serviceRegistry;

	
	
	public static SessionFactory createSessionFactory() {
	    Configuration configuration = new Configuration();
	    configuration.configure();
	    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
	            configuration.getProperties()).build();
	    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	    return sessionFactory;
	}
	

	
	public static <T> T runInSession(Operation<T> cmd){
		SessionFactory sessionFactory = SessionManager.createSessionFactory();
		Transaction transaction = null;
		T result = null;
		Session session = null;
		
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();

			tlSession.set(session);
			
			result = cmd.execute();

			session.flush();
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null)
				transaction.rollback();
			throw new RuntimeException(e);
		} finally {
			if (session != null)
				session.close();
			tlSession.set(null);
		}
		
		return result;
	}

	public static Session getSession() {
		return tlSession.get();
	}

}